import { useRef, useState } from "react";
import Taro, { useDidShow, useReachBottom, useRouter } from "@tarojs/taro";
import { Navigator, Text, View } from "@tarojs/components";
import { useUpdateEffect } from "ahooks";

import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import Moment from "@/components/app/Moment";
import Sticky from "@/components/app/Sticky";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import TabsTag from "@/components/app/TabsTag";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import CustomerCard from "@/components/app/CustomerCard";

import ApiCrm from "@/api/crm";
import ApiInspection from "@/api/inspection";
import useFetch from "@/hooks/useFetch";
import useList from "@/hooks/useList";

import { DailyInspection } from "@/types/Inspection";
import { IntentCustomerData } from "@/types/customer";
import { objectToQueryString } from "@/utils";

const RecordItem = ({
  type,
  source,
  intentCustomerId,
}: {
  type: string;
  source: DailyInspection;
  intentCustomerId: number;
}) => {
  return (
    <Navigator
      className="my-3"
      hoverClass="none"
      url={`/packageProject/pages/inspection/${type}?id=${
        source.id || source.recordMainId
      }&intentCustomerId=${intentCustomerId}`}
    >
      <Card>
        <ByRow align="center" content="between">
          <Text className="font-bold text-lg">
            {source.inspectionName || source.recordMainName}
          </Text>
        </ByRow>
        <ByRow align="center" content="between" className="mt-2 mb-1">
          <Text className="text-sm text-third">
            {source.inspectionUser || source.createUser}
          </Text>
          <Text className="text-sm text-third">
            业主{source.isCanSee ? "" : "不"}可见
          </Text>
        </ByRow>
        <ByRow align="center" content="between">
          <View
            className={
              source.unqualifiedNum == 0 ? "text-success" : "text-error"
            }
          >
            <Text>不合格：</Text>
            <Text className="font-bold">{source.unqualifiedNum}</Text>
          </View>

          <Moment className="text-sm text-third" value={source.createDate} />
        </ByRow>
      </Card>
    </Navigator>
  );
};

const tags = [{ label: "日常巡检" }, { label: "标准巡检" }];

export default () => {
  const isMounted = useRef(true);

  const { params } = useRouter<{ intentCustomerId: `${number}` }>();

  const intentCustomerId = +params.intentCustomerId;
  const [active, setActive] = useState<any>(0);

  const { data: statistic } = useFetch<{
    daily: number;
    standard: number;
    total: number;
  }>(ApiInspection.inspectionCount, { defaultParams: [{ intentCustomerId }] });

  // 日常 | 标准
  const {
    loading,
    list,
    total = 0,
    resetToFirst,
    nextPage,
  } = useList<DailyInspection>(
    () =>
      active
        ? ApiInspection.inspectionStandardList
        : ApiInspection.inspectionList,
    { defaultParams: [{ intentCustomerId }] }
  );

  useReachBottom(() => nextPage());

  useUpdateEffect(() => {
    resetToFirst({ intentCustomerId });
  }, [active]);

  const navigateTo = (type) => {
    const query = objectToQueryString({ intentCustomerId, index: total + 1 });

    Taro.navigateTo({
      url: `/packageProject/pages/inspection/${type}?${query}`,
    });
  };

  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res) => res.intentCustomer,
  });

  useDidShow(() => {
    if (!isMounted.current) {
      resetToFirst({ intentCustomerId });
    } else {
      isMounted.current = false;
    }
  });

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByRow content="center">
            <ByButton className="w-2/5" onClick={() => navigateTo("addDaliy")}>
              日常巡检
            </ByButton>
            <ByButton
              className="w-2/5"
              variant="outline"
              onClick={() => navigateTo("addStandard")}
            >
              标准巡检
            </ByButton>
          </ByRow>
        }
      >
        <CustomerCard source={data} />

        <Sticky position="top" className="bg-page p-3">
          <TabsTag
            mode="auto"
            items={tags}
            active={active}
            onChange={setActive}
          />
        </Sticky>

        <View className="p-3">
          <ByRow className="my-3">
            <ByCol span={6}>
              <Text>日常：{statistic?.daily}</Text>
            </ByCol>
            <ByCol span={6}>
              <Text>标准：{statistic?.standard}</Text>
            </ByCol>
          </ByRow>

          <ListView loading={loading} isEmpty={list.length === 0}>
            {list.map((item) => (
              <RecordItem
                source={item}
                key={item.id}
                intentCustomerId={intentCustomerId}
                type={active == 1 ? "standardDetail" : "detail"}
              />
            ))}
          </ListView>
        </View>
      </Page>
    </>
  );
};
